﻿#include <QPushButton>
#include <QTreeView>
#include <QPainter>
#include <QPaintEvent>
#include <QToolButton>

#include "filedialog.h"

FileDialog::FileDialog(QWidget *parent,const QString &path,const QString &title,const QString &filter)
    :QFileDialog(parent,Qt::Popup ),m_cancel(nullptr),m_ok(nullptr)
{
    //Qt::SubWindow Qt::Popup
    setAttribute(Qt::WA_TranslucentBackground);

    this->setOption(QFileDialog::DontUseNativeDialog);
    setWindowTitle(title);
    setDirectory(path);
    setNameFilter(filter);
    setViewMode(QFileDialog::Detail);
    setFileMode(QFileDialog::ExistingFiles);
    for(auto * obj: findChildren<QToolButton*>()){
        if(obj->toolTip() == "Back" || obj->toolTip() == u8"父目录"){
            continue;
        }
        obj->hide();
    }
    for(auto * button:findChildren<QPushButton*>()){
        if(button->text() == "&Open" || button->text() == u8"打开(&O)"){
            m_ok = button;
        }
        if(button->text() == "Cancel" || button->text() == u8"取消"){
            m_cancel = button;
            m_cancel->setText(u8"取消");
        }
    }
    if(m_ok){
        connect(m_ok,&QPushButton::clicked,this,&FileDialog::onOK);
    }
    m_treeView = findChild<QTreeView*>();
    if(m_treeView){
        connect(m_treeView,&QTreeView::doubleClicked,[&](QModelIndex index){
            if(index.flags() & Qt::ItemNeverHasChildren ){
                emit m_ok->click();
            }
        });
    }
}

FileDialog::~FileDialog()
{
}

void FileDialog::onClose()
{
    this->hide();
}
void FileDialog::onOK()
{
    if(m_ok){
        QStringList list;
        for(const auto & modelIndex:m_treeView->selectionModel()->selectedIndexes()){
            if(modelIndex.column() == 0){
                list.append(directory().absolutePath() +"/" + modelIndex.data().toString());
            }
        }
        emit emitFiles(list);
        hide();
    }
}

void FileDialog::hide()
{
    QFileDialog::hide();
}

void FileDialog::paintEvent(QPaintEvent * ev)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QPen pen;
    pen.setColor(QColor(255,255,255));
    pen.setWidth(0);
    painter.setPen(pen);
    painter.setBrush(Qt::white);
    QRect rect = this->rect();
    painter.drawRoundedRect(rect, 5, 5);

    QFileDialog::paintEvent(ev);
}
